<?php

namespace App\Listeners\Activity;

use App\Events\Cruise\CruiseOrderChangeEvent;
use App\Listeners\BaseListener;
use App\Models\Activity\ActivityShopJoinModel;
use App\Models\Cruise\CruiseOrderModel;
use App\Models\Cruise\CruiseOrderProcessV2Model;
use App\Remote\Rms\RmsUserRemote;
use App\Service\Activity\ShopActivityService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class SyncActivityStatusListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param CruiseOrderChangeEvent $event
     * @return void
     * @throws \Exception
     */
    public function handle(CruiseOrderChangeEvent $event)
    {
        try {
            $method = "handleTemplateType_{$event->templateType}";

            if (method_exists($this, $method)) {
                $this->{$method}($event);
            }
        } catch (\Exception $exception) {
            logException(
                "稽核表单状态同步事件订阅报错",
                $exception,
                [$event->cruiseOrderId],
                true, true
            );
        }
    }

    /**
     * 品牌运营项目
     *
     * @param CruiseOrderChangeEvent $event
     * @throws GuzzleException
     */
    public function handleTemplateType_9(CruiseOrderChangeEvent $event)
    {
        $cruiseOrderId = $event->cruiseOrderId;

        // 状态变更
        if (
            $event->newCruiseOrderModel
            &&
            $event->oldCruiseOrderModel
            &&
            $event->newCruiseOrderModel['status'] != $event->oldCruiseOrderModel['status']
        ) {

            switch ($event->newCruiseOrderModel['status']) {
                case CruiseOrderModel::STATUS_NOT_REVIEW:

                    // 待审核 - 更新参加状态&同步表单提交人信息
                    $lastProcessModel = CruiseOrderProcessV2Model::query()
                                                                 ->where("cruiseOrderId", $cruiseOrderId)
                                                                 ->where("cruiseOrderStatus",
                                                                     CruiseOrderModel::STATUS_NOT_SUBMIT)
                                                                 ->orderByDesc("id")
                                                                 ->first();

                    $update = [
                        "status"    => ActivityShopJoinModel::STATUS_1,
                        "updatedAt" => time()
                    ];
                    if ($lastProcessModel && $lastProcessModel->createdByUid) {
                        $user = RmsUserRemote::getRmsUserByIds([$lastProcessModel->createdByUid], ['id', 'username']);
                        if ($user) {
                            $update = array_merge($update, [
                                "submitUseId"    => $user[0]["id"],
                                "submitUsername" => $user[0]["username"],
                            ]);
                        }
                    }

                    Log::info("handleTemplateType_9....", ['id' => $event->cruiseOrderId, "update" => $update]);

                    ActivityShopJoinModel::query()->where("orderNo", $event->cruiseOrderId)->update($update);
                    break;
                case CruiseOrderModel::STATUS_NOT_MODIFY:
                    // 待修改 - 更新参加状态&同步表单审批人信息
                    $lastProcessModel = CruiseOrderProcessV2Model::query()
                                                                 ->where("cruiseOrderId", $cruiseOrderId)
                                                                 ->where("cruiseOrderStatus",
                                                                     CruiseOrderModel::STATUS_NOT_REVIEW)
                                                                 ->orderByDesc("id")
                                                                 ->first();

                    $update = [
                        "status"    => ActivityShopJoinModel::STATUS_2,
                        "updatedAt" => time()
                    ];
                    if ($lastProcessModel) {
                        $user = RmsUserRemote::getRmsUserByIds([$lastProcessModel->createdByUid], ['id', 'username']);
                        if ($user) {
                            $update = array_merge($update, [
                                "approveUseId"    => $user[0]["id"],
                                "approveUsername" => $user[0]["username"],
                            ]);
                        }
                    }
                    ActivityShopJoinModel::query()->where("orderNo", $event->cruiseOrderId)->update($update);
                    break;
                case CruiseOrderModel::STATUS_COMPLETE:

                    // 已完成 - 更新参加状态
                    ActivityShopJoinModel::query()->where("orderNo", $event->cruiseOrderId)->update([
                        "status"    => ActivityShopJoinModel::STATUS_3,
                        "joinTime"  => time(),
                        "updatedAt" => time()
                    ]);

                    // 把其他的join删了
                    $joinId = (int)ActivityShopJoinModel::query()->where("orderNo", $event->cruiseOrderId)->value('id');
                    ShopActivityService::closeOtherAction($joinId);

                    break;
            }
        }


    }
}
